// src/modules/users.ts
import axios from "axios";
import { UserData, DecodedToken, UserLoginData } from "@/types/userTypes"; // 引入用户类型
import { jwtDecode } from "jwt-decode";
import store from "@/store"; // 引入 Vuex store
import { getAccessToken } from "@/modules/auth"; // 引入 getAccessToken

const API_URL = "/api/users"; // 真实的 API URL
const MOCK_LOGIN_URL = "/mock/login"; // Mock 接口的 URL

export interface LoginResponse {
  status: string;
  data?: UserData; // 使用 UserData 类型
  message?: string;
  code: number;
}

export const loginUser = async (
  userData: UserLoginData
): Promise<LoginResponse> => {
  // 使用 Mock 接口
  const response = await axios.post<LoginResponse>(MOCK_LOGIN_URL, {
    params: {
      username: userData.username,
      password: userData.password,
      loginType: userData.loginType,
      phone: userData.phone,
      verificationCode: userData.verificationCode,
      autoLogin: userData.autoLogin,
    },
  });
  console.log(`loginUser: ${JSON.stringify(userData)}`);
  // const response = await axios.get<LoginResponse>(MOCK_LOGIN_URL);
  console.log(response.data);

  // 解码 accessToken
  if (response.data.data && response.data.data?.accessToken) {
    try {
      const decoded: DecodedToken = jwtDecode<DecodedToken>(
        response.data.data.accessToken
      );
      // 打印日志以调试参数
      console.log("(loginUser) Decoded Token:", decoded);
      console.log("Access Token:", response.data.data.accessToken);
      // 存储 token 到本地存储
      if (userData.autoLogin) {
        localStorage.setItem("accessToken", response.data.data.accessToken);
        localStorage.setItem(
          "userdata",
          JSON.stringify({
            username: userData.username,
            password: userData.password,
            loginType: userData.loginType,
            phone: userData.phone,
            autoLogin: userData.autoLogin,
          })
        );
      }
      // 打印 userData 以调试
      const _userData: UserData = {
        id: decoded.id,
        username: decoded.name,
        name: decoded.name,
        email: decoded.email,
        account: decoded.account,
        mode: decoded.mode,
        accessToken: response.data.data.accessToken,
        token: response.data.data.accessToken,
      };
      console.log("User Data being dispatched:", _userData);
      store.dispatch("users/login", {
        userData: _userData,
        token: response.data.data?.accessToken,
      });
      // 在登录成功后调用 getAccessToken
      await getAccessToken(); // 确保 token 是有效的，并更新状态
    } catch (error) {
      console.error("Token decoding error:", error);
    }
  }
  return response.data;
};
